package com.neu.wms.exception;



import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neu.wms.util.ResultVo;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

@RestControllerAdvice
@ResponseBody
public class GlobalException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo exceptionHandler(MethodArgumentNotValidException ex) throws JsonProcessingException {
        Map<String, String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(errors);
            return ResultVo.error(json);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResultVo handleIllegalArgumentException(IllegalArgumentException ex) throws JsonProcessingException {
        String errorMessage = ex.getMessage();
        Map<String, String> errors = Collections.singletonMap("error", errorMessage);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(errors);
        return ResultVo.error(json);
    }
}
